Reactive class property using stores

Posted on 2023-03-28 by

henrikvilhelmberglund

How can we turn a class property into a store? By default class properties do not give reactivity unless the class itself changes somehow.

Here we can see that the console.log() doesn't trigger.

1695743487041

<script>
	import { onMount } from "svelte";
	import Clock from "./clock";

	const clock = new Clock();

	onMount(() => {
		let interval = setInterval(() => {
			clock.tick();
		}, 1000);
		return () => clearInterval(interval);
	});

	let time;

	$: {
		time = clock.time;
		console.log("time", time);
	}
</script>

<p>{time}</p>

Which one is the best? Uh… I'll get back to you!